import page from "../apis/page";
import {action, observable, toJS} from "mobx";
import {message} from "antd";
import {WeaLocaleProvider} from "ecCom";
import app from '../apis/app';
import _ from 'lodash';

const getLabel = WeaLocaleProvider.getLabel;
const { error } = message;

export default class PublishStore {
  @observable publishSettings = {};//页面设置信息
  @observable wechatSettings = {};//发布到微信设置信息
  @observable submissionAuthority = [];//填写权限枚举
  @observable fillinFrequency = [];//填写票频率枚举
  @observable shortkey = ''; // 页面shortkey 用于表单访问的唯一标识
  @observable appid ='';
  @observable isCreate = false;
  @observable imgList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];//自定义图标列表
  @observable diyImg = '';//上传的自定义图标路径
  @observable isLoading = false;//是否正在上传图片
  @observable addShareVisible = false;

  @action getSetInfo = (appid) => {
    page.getSetInfo(appid).then(info => {
      info.startTime = info.startTime ? info.startTime : ' 00:00';
      info.endTime = info.endTime ? info.endTime : ' 00:00';
      if (info.makeUpEnable){
        const makeUpObj = JSON.parse(info.makeUp);

        info.makeUp = makeUpObj;
      }else {
        info.makeUp = { day: { type: '0', range: '0' }, week: { range: '0' } };
      }
      this.publishSettings = info;
      this.isCreate = false;
    }).catch(data => {
      if (data.api_errormsg === getLabel('503351','应用页面不存在')) {
        error(getLabel('503352','表单尚未创建, 暂不能发布') );
        this.isCreate = true;
        this.publishSettings = {};
      }
    });
    this.imgList = this.imgList.map((val,i) => {
      return '/edc/images/wechat-'+(i+1)+'.png';
    });
    page.getWxInfo(appid).then(info => {
      this.wechatSettings = info;
      if(this.wechatSettings.imgUrl){
        if(this.imgList.indexOf(this.wechatSettings.imgUrl)<0){
          this.diyImg = this.wechatSettings.imgUrl;
        }
      }else{
        this.wechatSettings.imgUrl = '/edc/images/wechat-1.png';
      }
    });
    if(this.appid===appid) return;
    this.appid = appid;
    this.getPagekey(this.appid);
  }

  @action getPagekey = appid => {
    page.getShortKey(appid).then(shortkey => {
      this.shortkey = shortkey;
    }).catch(error => {});
  }

  @action setUpdate = () => {
    let data = toJS(this.publishSettings);
    data.appid = this.appid;
    Object.keys(data).map(v =>{
      if (_.isObject(data[v])){
        data[v] = JSON.stringify(data[v]);
      }else {
        data[v] = data[v] && data[v].toString() ? data[v].toString() : '';
      }
    });
    return Promise.all([
      page.setUpdate(data),
      this.setWxUpdate(),
    ]);
  }

  @action setWxUpdate = () => {
    let data = toJS(this.wechatSettings);
    data.appid = this.appid;
    Object.keys(data).map(v =>{
      this.wechatSettings[v] = data[v];
      data[v] = data[v]&&data[v].toString() ? data[v].toString() : '';
    })
    return page.wxUpdate(data);
  }

  //上传微信自定义图标
  @action uploadImg = data => {
    this.isLoading = true;
    page.uploadImg(data).then(res => {
      this.wechatSettings.imgUrl = res.image;
      this.diyImg = res.image;
      this.isLoading = false;
    });
  }

  @action onSetChange = (key,value) => {
    switch(key){
      case 'fillinEnabled':
      case 'timeRangeEnabled':
      case 'dataUpperLimitEnabled':
      case 'dailyTimeRangeEnabled':
      case 'editEnabled':
      case 'makeUpEnable':
      case 'timeLimitEnable':
        value = value==='1' ? true : false;
        break;
      case 'startDate':
      case 'endDate':
        key = key==='startDate' ? 'startTime' : 'endTime';
        const dd = this.publishSettings[key].split(' ');
        value = value +' '+ (dd.length === 2 ? dd[1] : '');
        break;
      case 'startTime':
      case 'endTime':
        value = this.publishSettings[key].split(' ')[0] + ' ' + value;
        break;
      case 'timeLimit': {
        const { timeLimit } = this.publishSettings;
        let tempTimeLimit = timeLimit ? JSON.parse(timeLimit) : {};

        tempTimeLimit = { ...tempTimeLimit, ...value };
        value = JSON.stringify(tempTimeLimit);
        break;
      }
      case 'dataApplyPerson':
      case 'dataMsgReminder': {
        value = JSON.stringify(value);
        break;
      }
    }
    if (key.indexOf('makeUp') > -1) {
      const tempArr = key.split(':');
      const { makeUp: oldRepairConfig } = this.publishSettings;

      key = tempArr[0];
      if (tempArr[1] === 'day' || tempArr[1] === 'week') {
        const tempRepairObj = oldRepairConfig[tempArr[1]];

        oldRepairConfig[tempArr[1]] = { ...tempRepairObj, [tempArr[2]]: value }
        value = { ...oldRepairConfig }
      }
    }

    if(this.publishSettings[key]===value) return;
    this.publishSettings[key] = value;
  }

  @action getSubmissionAuthority = () => {
    if (this.submissionAuthority.length) return;

    page.getSubmissionAuthority().then(data => {
      this.submissionAuthority = data;
    });
  }

  @action setWechat = (key,value) => {
    this.wechatSettings[key] = value;
  }

  @action getFillinFrequency = () => {
    if (this.fillinFrequency.length) return;

    page.getFillinFrequency().then(data => {
      this.fillinFrequency = data;
    });
  }

  @action showAddShareDialog = () => {
    this.changePermissionType('SPECIFIED_USER');
  }

  @action hideAddShareDialog = () => {
    this.addShareVisible = false;
  }

  @action changePermissionType = value => {
    app.submitAuthChange({
      appid: this.appid,
      submissionAuthority: value
    }).then(res => {
      this.addShareVisible = true;
    });
  }
}